<script setup lang="ts">
import { getFlowerOptions } from "@/api/flower";
import { isEmpty } from "@pureadmin/utils";
import type { FlowerOptionItem } from "types/flower";
import { onMounted, ref } from "vue";

const modelValue = defineModel<string[]>({ default: () => [] });

const flowerList = ref<FlowerOptionItem[]>([]);

let flowerMap: Record<number, FlowerOptionItem> = {};

const checkList = ref<number[]>([]);

const visible = ref(false);

const handleConfirm = () => {
  visible.value = false;
  modelValue.value = checkList.value.map(id => {
    return flowerMap[id].name;
  });
};

const handleReset = () => {
  visible.value = false;
  checkList.value = [];
  modelValue.value = [];
};

onMounted(() => {
  getFlowerOptions().then(res => {
    flowerList.value = res;
    flowerMap = res.reduce((map: Record<number, FlowerOptionItem>, item) => {
      map[item.id] = item;
      return map;
    }, {});
  });
});
</script>
<template>
  <el-popover
    v-model:visible="visible"
    placement="bottom"
    :width="200"
    title="筛选商品"
    trigger="click"
  >
    <template #reference>
      <span
        class="cursor-pointer flex items-center justify-center"
        :style="{
          color: isEmpty(checkList)
            ? 'var(--el-text-color-secondary)'
            : 'var(--el-color-primary)'
        }"
      >
        商品
        <IconifyIconOnline icon="ep:arrow-down" />
      </span>
    </template>
    <div>
      <el-scrollbar height="160px">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in flowerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-checkbox-group>
      </el-scrollbar>
      <el-space class="mt-2">
        <el-button size="small" @click="handleConfirm">筛选</el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </el-space>
    </div>
  </el-popover>
</template>
<style scoped lang="scss">
:deep(.el-checkbox-group) {
  .el-checkbox {
    width: 100%;
    margin: 0;

    .el-checkbox__label {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }
  }
}
</style>
